import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserLog, UserActionType } from '../entities/user-log.entity';
import { PaginationDto } from '../../../common/dto/pagination.dto';

@Injectable()
export class UserLogService {
  private readonly logger = new Logger(UserLogService.name);

  constructor(
    @InjectRepository(UserLog)
    private readonly userLogRepository: Repository<UserLog>,
  ) {}

  /**
   * 记录用户行为日志
   * @param logData 日志数据
   */
  async logUserAction(logData: Partial<UserLog>): Promise<UserLog> {
    try {
      const log = this.userLogRepository.create(logData);
      return await this.userLogRepository.save(log);
    } catch (error) {
      this.logger.error('记录用户行为日志失败', error.stack);
      throw error;
    }
  }

  /**
   * 记录用户登录
   */
  async logUserLogin(
    userId: string,
    username: string,
    ipAddress?: string,
    userAgent?: string,
  ): Promise<UserLog> {
    return this.logUserAction({
      userId,
      username,
      actionType: UserActionType.LOGIN,
      actionDescription: '用户登录',
      ipAddress,
      userAgent,
    });
  }

  /**
   * 记录用户登出
   */
  async logUserLogout(
    userId: string,
    username: string,
    ipAddress?: string,
    userAgent?: string,
  ): Promise<UserLog> {
    return this.logUserAction({
      userId,
      username,
      actionType: UserActionType.LOGOUT,
      actionDescription: '用户登出',
      ipAddress,
      userAgent,
    });
  }

  /**
   * 记录用户创建操作
   */
  async logUserCreate(
    userId: string,
    username: string,
    resourceId: string,
    requestUrl?: string,
    requestMethod?: string,
    requestParams?: any,
    executionTime?: number,
    ipAddress?: string,
    userAgent?: string,
  ): Promise<UserLog> {
    return this.logUserAction({
      userId,
      username,
      actionType: UserActionType.CREATE,
      actionDescription: '创建用户',
      resourceType: 'user',
      resourceId,
      requestUrl,
      requestMethod,
      requestParams,
      executionTime,
      ipAddress,
      userAgent,
    });
  }

  /**
   * 记录用户更新操作
   */
  async logUserUpdate(
    userId: string,
    username: string,
    resourceId: string,
    requestUrl?: string,
    requestMethod?: string,
    requestParams?: any,
    executionTime?: number,
    ipAddress?: string,
    userAgent?: string,
  ): Promise<UserLog> {
    return this.logUserAction({
      userId,
      username,
      actionType: UserActionType.UPDATE,
      actionDescription: '更新用户',
      resourceType: 'user',
      resourceId,
      requestUrl,
      requestMethod,
      requestParams,
      executionTime,
      ipAddress,
      userAgent,
    });
  }

  /**
   * 记录用户删除操作
   */
  async logUserDelete(
    userId: string,
    username: string,
    resourceId: string,
    requestUrl?: string,
    requestMethod?: string,
    requestParams?: any,
    executionTime?: number,
    ipAddress?: string,
    userAgent?: string,
  ): Promise<UserLog> {
    return this.logUserAction({
      userId,
      username,
      actionType: UserActionType.DELETE,
      actionDescription: '删除用户',
      resourceType: 'user',
      resourceId,
      requestUrl,
      requestMethod,
      requestParams,
      executionTime,
      ipAddress,
      userAgent,
    });
  }

  /**
   * 记录用户批量删除操作
   */
  async logUserBatchDelete(
    userId: string,
    username: string,
    requestUrl?: string,
    requestMethod?: string,
    requestParams?: any,
    executionTime?: number,
    ipAddress?: string,
    userAgent?: string,
  ): Promise<UserLog> {
    return this.logUserAction({
      userId,
      username,
      actionType: UserActionType.BATCH_DELETE,
      actionDescription: '批量删除用户',
      resourceType: 'user',
      requestUrl,
      requestMethod,
      requestParams,
      executionTime,
      ipAddress,
      userAgent,
    });
  }

  /**
   * 根据多个条件分页查询用户行为日志
   */
  async findUserLogsWithFilters(
    filters: {
      userId?: string;
      actionType?: UserActionType;
      apiName?: string;
    },
    paginationDto: PaginationDto,
  ): Promise<[UserLog[], number]> {
    const { page = 1, pageSize = 10 } = paginationDto;
    const skip = (page - 1) * pageSize;

    // 构建查询条件
    const whereConditions: any = { isDeleted: false };
    
    if (filters.userId) {
      whereConditions.userId = filters.userId;
    }
    
    if (filters.actionType) {
      whereConditions.actionType = filters.actionType;
    }
    
    if (filters.apiName) {
      whereConditions.apiName = filters.apiName;
    }

    return await this.userLogRepository.findAndCount({
      where: whereConditions,
      order: { createdAt: 'DESC' },
      skip,
      take: pageSize,
    });
  }

  /**
   * 清理旧的用户日志
   * @param days 保留天数，默认90天
   * @returns 清理的记录数量
   */
  async cleanOldLogs(days: number = 90): Promise<number> {
    try {
      const cutoffDate = new Date();
      cutoffDate.setDate(cutoffDate.getDate() - days);

      const result = await this.userLogRepository
        .createQueryBuilder()
        .update(UserLog)
        .set({ isDeleted: true })
        .where('createdAt < :cutoffDate', { cutoffDate })
        .andWhere('isDeleted = :isDeleted', { isDeleted: false })
        .execute();

      const deletedCount = result.affected || 0;
      this.logger.log(`清理旧用户日志成功: ${deletedCount} 条记录`);
      return deletedCount;
    } catch (error) {
      this.logger.error(`清理旧用户日志失败: ${error.message}`, error.stack);
      throw error;
    }
  }
} 